package com.example.back.config;

import com.example.back.utils.UserUtils;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.zaxxer.hikari.HikariDataSource;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;

import org.javers.spring.auditable.AuthorProvider;
import org.javers.spring.auditable.MockAuthorProvider;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;

import javax.annotation.Resource;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
@EnableJpaRepositories(value = {"com.example.back.jpa"}, transactionManagerRef = "jpaTransactionManager")
public class BasicConfig {
    @Resource
    private HikariDataSource dataSource;
    @Resource
    private UserUtils userUtils;

    /**
     * JPA事务管理器
     */
    @Bean("jpaTransactionManager")
    public JpaTransactionManager jpaTransactionManager() {
        JpaTransactionManager jpa = new JpaTransactionManager();
        jpa.setDataSource(dataSource);
        jpa.setRollbackOnCommitFailure(true);
        return jpa;
    }

    /**
     * 指定feign-client encoder
     */
    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder();
    }
    
    // 指定当前操作人ID
    @Bean
    public AuthorProvider authorProvider() {
        return new MockAuthorProvider() {
            @Override
            public String provide() {
                if(userUtils.getUserID() == null)
                    return "0";
                return userUtils.getUserID().toString();
            }
        };
    }

    /**
     * 图片验证码
     */
    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.image.width", "150");
        properties.put("kaptcha.image.height", "40");
        properties.put("kaptcha.textproducer.font.size", "30");
        properties.put("kaptcha.session.key", "ValidateCode");
        properties.put("kaptcha.textproducer.char.space", "5");
        Config config = new Config(properties);
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}
